Understanding Margin Collapsing in CSS
Margin collapsing occurs when the vertical margins of two or more block-level elements combine into a single margin instead of adding up. This often leads to unexpected spacing issues in layouts.
In this case, the bottom margin of the <h1> (40px) and the top margin of the <p> (30px) collapse into one margin equal to the larger of the two (40px). This can create confusion when designing consistent vertical spacing.
Between adjacent block-level elements (e.g., <h1> and <p>).
Between a parent and its first or last child when there’s no border or padding.
In empty blocks where top and bottom margins meet.
You can prevent margin collapsing by adding padding, a border, or using overflow: auto or display: flow-root on the parent element.